package org.aliwo.concurrency;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 学习
 *
 * await() 进入阻塞状态，直到所有线程完成工作，然后继续往下执行
 * countDown() 减1
 * 应用场景：线程同步，多个线程等待，只有所有线程完成工作，主线程才能继续往下执行，否则阻塞
 *  启动三个线程计算，需要对结果进行累加。
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(8);

//        new Thread(()->{
//            try {
//                countDownLatch.await();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println("800米比赛结束， 准备清空跑到");
//        }).start();

        for (int i = 0; i < 8; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    Thread.sleep(finalI * 1000);
                    System.out.println("线程" + Thread.currentThread().getName() + "到达终点");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    countDownLatch.countDown();
                }
            }).start();
        }

//        new Thread(()->{
//            try {
//                countDownLatch.await();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println("800米比赛结束， 准备清空跑到");
//        }).start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("800米比赛结束， 准备清空跑到");
    }
}
